<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 前台订单ajax
 * @package  ajax
 * @subpackage  shop
 * create by allen.qiang
 */

quanli_require('module/base/shop/shopCart.class.php');
quanli_require('module/base/bill/billCheckout.class.php');
quanli_require('module/base/activity/activityConfig.class.php');

class ajax_checkout {

    private $bill_array;    //购物车数组

    private $cust_buy_log; //会员购买记录

    private $source;        //来源

    private $pcustID;       //会员号

    private $act;           //购物车名

    private $noon = '13:00:00';     //上午、下午时间界限

    public function execute() {

        global $G_SHOP;

        //订单来源
        if(isset($_REQUEST['source']) && !empty($_REQUEST['source'])){
            $this->source = $_REQUEST['source'];
        }else{
            $this->source = 'web';
        }

        //购物车名
        if (isset($_REQUEST['act']) && !empty($_REQUEST['act'])) {
            $this->act = $_REQUEST['act'];
        } else {
            $this->act = 'shop_cart';
        }

        if(isset($_REQUEST['buy_log']) && !empty($_REQUEST['buy_log'])){
            $this->cust_buy_log = $_REQUEST['buy_log'];
        }else{
            $this->cust_buy_log = '';
        }

        $this->pcustID = $G_SHOP->currentPCustID;

        $this->getBillArray();

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //收货地址、配送方式、支付方式、付款方式、发票
                    $this->load();
                    break;

                case 2: //查询收货地址，并根据收货地址查询配送方式和支付方式、付款方式
                    $this->loadFromAddress();
                    break;

                case 3: //查询配送站
                    $this->searchDeliveryTerminal();
                    break;

                case 4: //获取配送时间
                    $this->getDeliveryTime();
                    break;

                case 5: //使用积分
                    $this->usePoints();
                    break;

                case 6: //使用代金卡
                    $this->useCard();
                    break;

                case 7: //使用优惠券
                    $this->useCoupon();
                    break;

                case 8: //取消使用积分
                    $this->cancelUsePoints();
                    break;

                case 9: //查询账户红包、券
                    $this->couponByUseType();
                    break;

                case 10: //总计算
                    $this->totalCount();
                    break;

                case 11: //更改配送时间
                    $this->setDeliveryTime();
                    break;

                case 12: //pc端选择支付方式或付款方式
                    $this->choosePay();
                    break;

                case 13: //购买配件
                    $this->buyFittings();
                    break;

                case 14: //加载商品
                    $this->loadGoods();
                    break;

                case 15: //取消现金卡
                    $this->cancelUseCard();
                    break;

                case 16: //使用红包
                    $this->useRedBag();
                    break;

                case 17: //取消使用优惠券
                    $this->cancelUseCoupon();
                    break;

                case 18: //记录收货地址
                    $this->setdeliverID();
                    break;

                case 19: //wap端记录支付方式和付款方式
                    $this->setPayType();
                    break;

                case 20: //记录生日牌
                    $this->setBirthdayCard();
                    break;

                case 21: //记录订单备注
                    $this->setBillRemark();
                    break;

                case 22: //wap会员发票设置
                    $this->setBillInvoice();
                    break;

                case 23: //wap配送时间
                    $this->wapDeliveryTime();
                    break;
                //add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --start
                case 24: //查询爆单时间
                	$this->baodan();
                	break;
               	//add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --end
                //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 start
                case 25:
                    //$this->preSale();
                    break;
                case 26:
                    $this->pre_sale();
                    break;
                //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 end

                //add by 20141222 wanglulu   记录生日牌、生日蜡烛选择状态 --start
                case 27:
                    $this->bs_ck();
                    break;

                case 28:
                    $this->candle_ck();
                //add by 20141222 wanglulu   记录生日牌、生日蜡烛选择状态 --end

                //add by 2015-01-22 allen.qiang FUN-AC-0037-情人节活动 ---start
                case 29: //总计算
                    $this->totalCount_valentine();
                    break;
                //add by 2015-01-22 allen.qiang FUN-AC-0037-情人节活动 ---end
                default:
                    returnJsonData('参数错误');
                    break;

            }

        } else {

            returnJsonData('参数错误');

        }

    }

    /**
     * 获取购物车数据
     */
    private function getBillArray(){

        //实例购物车类
        $shopCart = new shopCart();

        $this->bill_array = $shopCart->getCartInfo( $this->act );

    }

    /**
     * 保存购物车数据
     */
    private function setBillArray( $c = null, $data = null ){

        //实例购物车类
        $shopCart = new shopCart();
        $shopCart->setCartInfo($this->bill_array, $this->act);

        if (!is_null($c)) {

            $c['log'] = $this->cust_buy_log;

            returnJsonData('ok', 200, $c);

        } else {

            returnJsonData('ok', 200, $data);

        }

    }

    /**
     * 判断会员登陆状态
     * 1、游客 2、老会员未使用密码登陆 0、正常登陆会员
     */

    private function login_status(){

        global $G_SHOP;

        if($G_SHOP->isGuest == 1){

            returnJsonData('您还没有设定密码，请先设定密码!');

        }elseif($G_SHOP->isGuest == 2){

            returnJsonData('积分、红包、优惠券需要登陆后才可以使用，请先登录!');
        }

    }

    /**
     * 判断会员登陆状态
     * 1、游客 2、老会员未使用密码登陆 0、正常登陆会员
     */


    /**
     * 加载购物车商品
     */
    private function loadGoods(){

        if(isset($this->bill_array['goods']['general']) && !empty($this->bill_array['goods']['general'])){
            $goods_array = &$this->bill_array['goods']['general'];
        }else{
            $goods_array = array();
        }

        foreach($goods_array as &$goods){

            $goods['price'] = floatval($goods['price']);
            $goods['use_card'] = array();
            $goods['card_deducation'] = 0;

            if(!isset( $goods['buyFittings'] ) || empty( $goods['buyFittings'])){
                $goods['buyFittings'] = array();
            }

        }

        $this->setBillArray(null,$goods_array);
    }

    /**
     * 收货地址、配送方式、支付方式、付款方式、发票
     */
    private function load(){

        global $G_SHOP;

        //城市id
        $city_id = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');
        $this->bill_array['master']['cityid'] = $city_id;

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        //判断是否有活动
        $haveActivity = false;

        //实例活动配置类
        $activityConfig = new activityConfig($this->act);

        $config = $activityConfig->config;

        if($config && isset($config['start_time'],$config['end_time']) && date('Y-m-d H:i:s') > $config['start_time'] && date('Y-m-d H:i:s') < $config['end_time']){
            $haveActivity = true;
        }

        try {

            //发票
            $c['invoice'] = $billCheckout->getInvoiceList($this->bill_array['master'], $this->cust_buy_log);

            //收货地址
            $c['deliver'] = $billCheckout->getDeliverList($this->bill_array['master'], $this->cust_buy_log );

            if (!$c['deliver']) {
                $this->setBillArray( $c );
            }

            //根据用户登录状态显示
            if( in_array($G_SHOP->isGuest, array(1, 2)) ){
                foreach($c['deliver'] as &$deliver){

                    $address_last = mb_substr($deliver['address'], -1, 1, 'utf-8');
                    $address_first = mb_substr($deliver['address'],  0, 1, 'utf-8');

                    $mobile_first = mb_substr($deliver['mobile'], 0, 1, 'utf-8');
                    $mobile_last = mb_substr($deliver['mobile'], -1, 1, 'utf-8');

                    $deliver['address'] = $address_first.'********'.$address_last;
                    $deliver['custName'] = '***';
                    $deliver['mobile'] = $mobile_first.'********'.$mobile_last;
                }
            }

            //配送站
            $billCheckout->getDistributionList( $this->bill_array['master'] );

            //配送方式
            $c['send'] = $billCheckout->getSendTypeList( $this->bill_array['master'], $this->cust_buy_log);
            if (!$c['send']) {
                $this->setBillArray( $c );
            }

            /*
             * 前端支付方式显示的数据内容，后台活动配置功能做好后启用这段代码 add by allen.qiang Start */

            //前端支付方式显示 add by allen.qiang Start
            $payTypeID = $paymentID = '';//默认条件为空查询所有

            //活动支持的付款方式
            $payTypeID .= $haveActivity && isset($config['payTypeID']) && !empty($config['payTypeID']) ? $config['payTypeID'] : '';
            $paymentID .= $haveActivity && isset($config['paymentID']) && !empty($config['paymentID']) ? $config['paymentID'] : '';

            $extend1 = !empty($payTypeID)?" AND payTypeID IN({$payTypeID})":'';
            $extend2 = !empty($paymentID)?" AND id IN({$paymentID})":'';

            //仅保留活动支持的付款方式和支付方式
            $c['pay'] = $billCheckout->getPayTypeList($this->source, $this->bill_array['master'], $this->cust_buy_log, $extend1, $extend2);

            /*
             * 前端支付方式显示的数据内容，后台活动配置功能做好后启用这段代码 add by allen.qiang End */

            if (!$c['pay']) {
                $this->setBillArray( $c );
            }

            //付款方式
            $c['m_pay'] = $billCheckout->getPaymentMethodList($this->bill_array['master']);
            if (!$c['m_pay']) {
                $this->setBillArray( $c );
            }

            $this->setBillArray( $c );

        } catch (Exception $e) {

            error_log($e->getMessage());
            returnJsonData('系统错误', 500);

        }

    }

    /**
     * 查询收货地址，并根据收货地址查询配送方式和支付方式、付款方式
     */
    private function loadFromAddress(){

        if (!isset($_REQUEST['deliverID']) || !is_numeric($_REQUEST['deliverID'])) {
            returnJsonData('参数错误', 400);
        }

        global $G_SHOP;

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        //判断是否有活动
        $haveActivity = false;

        //实例活动配置类
        $activityConfig = new activityConfig($this->act);

        $config = $activityConfig->config;

        if($config && isset($config['start_time'],$config['end_time']) && date('Y-m-d H:i:s') > $config['start_time'] && date('Y-m-d H:i:s') < $config['end_time']){
            $haveActivity = true;
        }

        try {

            //查询会员收货地址
            if (!$billCheckout->getDeliver( $this->bill_array['master'], $this->cust_buy_log, $_REQUEST['deliverID'] )) {
                throw new Exception('收货地址信息没有找到，请选择其他收货地址', 404);
            }

            unset($this->bill_array['master']['sendTypeID']);
            unset($this->bill_array['master']['payTypeID']);
            unset($this->bill_array['master']['payTypeName']);
            unset($this->bill_array['master']['pay_type']);
            unset($this->bill_array['master']['payment_method_id']);
            unset($this->bill_array['master']['payment_method_name']);
            unset($this->bill_array['master']['payment_method_type']);

            //配送站
            $billCheckout->getDistributionList( $this->bill_array['master'] );

            //配送方式
            $c['send'] = $billCheckout->getSendTypeList( $this->bill_array['master'], $this->cust_buy_log );
            if (!$c['send']) {
                $this->setBillArray( $c );
            }

            /*
             * 前端支付方式显示的数据内容，后台活动配置功能做好后启用这段代码 add by allen.qiang Start */

            //前端支付方式显示 add by allen.qiang Start
            $payTypeID = $paymentID = '';//默认条件为空查询所有

            //活动支持的付款方式
            $payTypeID .= $haveActivity && isset($config['payTypeID']) && !empty($config['payTypeID']) ? $config['payTypeID'] : '';
            $paymentID .= $haveActivity && isset($config['paymentID']) && !empty($config['paymentID']) ? $config['paymentID'] : '';

            $extend1 = !empty($payTypeID)?" AND payTypeID IN({$payTypeID})":'';
            $extend2 = !empty($paymentID)?" AND id IN({$paymentID})":'';

            //仅保留活动支持的付款方式和支付方式
            $c['pay'] = $billCheckout->getPayTypeList($this->source, $this->bill_array['master'], $this->cust_buy_log, $extend1, $extend2);

            /*
             * 前端支付方式显示的数据内容，后台活动配置功能做好后启用这段代码 add by allen.qiang End */

            if (!$c['pay']) {
                $this->setBillArray( $c );
            }

            $this->setBillArray( $c );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                returnJsonData( $e->getMessage(), $e->getCode() );
            } else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500);
            }

        }
    }

    /**
     * 查询配送站
     */
    private function searchDeliveryTerminal(){

        if(!isset($_REQUEST['cityid']) || empty($_REQUEST['cityid'])){
            returnJsonData('参数错误');
        }

        $cityid = intval($_REQUEST['cityid']);

        quanli_require('module/base/system/sysDistribution.class.php');

        //实例化配送站
        $sysDistribution = new sysDistribution();

        $arg_array = array(
            'cityid' => $cityid,
            'extend' => ' AND (distribution_type = 2 OR distribution_type = 3)',
            'useFlg' => 1
        );

        //查询配送站
        $distribution_array = $sysDistribution->search( $arg_array );

        returnJsonData('ok', 200, $distribution_array);
    }

    /**
     * 获取配送时间
     */
    private function getDeliveryTime() {

        quanli_include('module/base/system/itemHandler.class.php');

        $send_date = $this->bill_array['master']['send_date'];

        if (!isset($_REQUEST['date']) || empty($_REQUEST['date'])) {
            $_REQUEST['date'] = $send_date;
        }

        if ($_REQUEST['date'] == $send_date) {
            $send_start_time = $this->bill_array['master']['check_send_start_time'];
            $send_end_time = $this->bill_array['master']['check_send_end_time'];
        } else {
            $send_start_time = $this->bill_array['master']['check_start_deliver_time'];
            $send_end_time = $this->bill_array['master']['check_end_deliver_time'];
        }

        if(isset($_REQUEST['time_quantum']) && !empty($_REQUEST['time_quantum'])){
            $time_quantum = $_REQUEST['time_quantum'];
        }

        //实例化字典类
        $itemHandler = new itemHandler();

        //实例订单结算类
        $billCheckout = new billCheckout();

        //返回数组
        $return_array = array(
            'time' => array(),
            'send_start_time'=> array(),
            'send_end_time'=> array(),
            'time_select' => isset($time_quantum) ? $time_quantum : ''
        );

        //配送开始时间查询参数
        $arg_array = array(
            'itemCategoryID' => 9,
            'useFlg' => 1
        );

        //配送开始时间
        $start_time_array = $itemHandler->searchItem( $arg_array );

        //配送结束时间
        $arg_array = array(
            'itemCategoryID' => 10,
            'useFlg' => 1
        );
        $end_time_array = $itemHandler->searchItem( $arg_array );

        if($send_end_time == '00:00:00'){
            $send_end_time = '23:59:59';
        }

        //配送站id
        $distribution_id = $this->bill_array['master']['distribution_id'];

        //添加自定义配送时间段功能 add by allen.qiang 2015-05-07 Start

        $act = $_REQUEST['act'];

        if($act && !empty($act)){

            $activityConfig = new activityConfig($act);

            $config = $activityConfig->config;

            if($config && $config['custom_send_time']!=''){

                $custom_send_time = (array)json_decode($config['custom_send_time']);

                $send_start_time = $startTime = $custom_send_time['send_start_time'];
                $send_end_time = $endTime = $custom_send_time['send_end_time'];

                $start_time_array = $end_time_array = array();

                $start_time_array[] = array( 'itemName'=>$startTime);//第一个开始时间
                $end_time_array[] = array( 'itemName'=>$endTime);//第一个结束时间

            }
        }

        //添加自定义配送时间段功能 add by allen.qiang 2015-05-07 End

        //配送时间起始时间段
        foreach( $start_time_array as &$time ){

            $itemName = $time['itemName'];

            if($itemName < $send_start_time || $itemName >= $send_end_time)
                continue;

            if($itemName <= $this->noon && !in_array('上午', $return_array['time']))
                $return_array['time'][] = '上午';

            if($itemName >= $this->noon && !in_array('下午', $return_array['time']))
                $return_array['time'][] = '下午';

            if(!isset($time_quantum) && in_array('上午', $return_array['time']) && $itemName > $this->noon)
                continue;

            if(isset($time_quantum) && $time_quantum == '上午' && $itemName > $this->noon)
                continue;

            if(isset($time_quantum) && $time_quantum == '下午' && $itemName < $this->noon)
                continue;

            $check_result_array = $billCheckout->checkDistributionSendRestrict( $_REQUEST['date'], $itemName, $distribution_id );

            if ($check_result_array['s'] == 0)
                continue;

            if ($check_result_array['h'] == 1) {
                $itemName .= '(爆单)';
            }

            $return_array['send_start_time'][] = $itemName;

        }

        //配送时间结束时间
        foreach( $end_time_array as &$time ){

            if($time['itemName'] > $send_end_time)
                continue;

            $return_array['send_end_time'][] = $time['itemName'];

        }

        returnJsonData('ok', 200, $return_array);

    }

    /**
     * wap配送时间
     */
    private function wapDeliveryTime(){

        global $G_SHOP;

        quanli_require('module/base/system/itemHandler.class.php');

        //实例化字典类
        $itemHandler = new itemHandler();

        //实例订单结算类
        $billCheckout = new billCheckout();

        $return_array = array( );

        $send_date = $this->bill_array['master']['send_date'];
        if(!isset($_REQUEST['date']) || empty($_REQUEST['date'])){
            $_REQUEST['date'] = $send_date;
        }

        if ($send_date == $_REQUEST['date']) {
            $send_start_time = $this->bill_array['master']['check_send_start_time'];
            $send_end_time = $this->bill_array['master']['check_send_end_time'];
        } else {
            $send_start_time = $this->bill_array['master']['check_start_deliver_time'];
            $send_end_time = $this->bill_array['master']['check_end_deliver_time'];
        }

        //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 start
        $dataArray=array(
            'date'=>$_REQUEST['send_date']
        );
        $iserror=$this->preSale($dataArray);
//        if($iserror==400){
//            returnJsonData('抱歉，该日的拿破仑莓恋已爆单，您可选择其他的配送日期');
//        }
        //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 end



        //配送开始时间查询参数
        $arg_array = array(
            'itemCategoryID' => 9,
            'useFlg' => 1
        );

        //配送开始时间
        $start_time_array = $itemHandler->searchItem( $arg_array );

        if($send_end_time == '00:00:00'){
            $send_end_time = '23:59:59';
        }

        if($send_date == $_REQUEST['date']){
            foreach($start_time_array as &$time){
                if ($time['itemName'] >= $send_start_time && $time['itemName'] <= $send_end_time) {
                    $return_array[] = $time['itemName'];
                }
            }
        }else{
            foreach($start_time_array as &$time){

                $return_array[] = $time['itemName'];
            }
        }

        $item_array = array();

        //配送站id
        $distribution_id = $this->bill_array['master']['distribution_id'];

        //添加自定义配送时间段功能 add by allen.qiang 2015-05-07 Start

        $act = $_REQUEST['act'];

        if($act && !empty($act)){

            $activityConfig = new activityConfig($act);

            $config = $activityConfig->config;

            if($config && $config['custom_send_time']!=''){

                $custom_send_time = (array)json_decode($config['custom_send_time']);

                $send_start_time = $custom_send_time['send_start_time'];
                $send_end_time = $custom_send_time['send_end_time'];

//                $return_array = array();
//
//                $return_array[] = $send_start_time;//第一个开始时间
//                $return_array[] = $send_end_time;//第一个开始时间

//                while($send_start_time<$send_end_time){
//                    $send_start_time = date("H:i:s", strtotime("$send_start_time +30 min"));
//                    $return_array[] = $send_start_time;
//                }

                $item_array[] = array(
                    'time_name' => '上午'.$send_start_time.'~'.$send_end_time,
                    'send_start_time' => $send_start_time,
                    'send_end_time' => $send_end_time
                );


                $this->setBillArray(null, $item_array);

            }

        }

        //添加自定义配送时间段功能 add by allen.qiang 2015-05-07 End

        foreach($return_array as &$time){

            if($time >= $send_end_time)
                continue;

            if($time >= $this->noon){
                $d = '下午';
            }else{
                $d = '上午';
            }

            $check_result_array = $billCheckout->checkDistributionSendRestrict( $_REQUEST['date'], $time, $distribution_id );

           
            if($_REQUEST['date']=='2015-02-18' && $time > '17:30:00')
            {
                continue;
            }
            if ($check_result_array['s'] == 0) {
                continue;
            }

            $end_time = date('H:i:s', strtotime( $time ) + 1800);
            if ($check_result_array['h'] == 1) {
                $time_name = $d . $time . '~' . $end_time . '(爆单)';
            } else {
                $time_name = $d . $time . '~' . $end_time;
            }

            $item_array[] = array(
                'time_name' => $time_name,
                'send_start_time' => $time,
                'send_end_time' => $end_time
            );
        }

        $this->setBillArray(null, $item_array);

    }

    //更该配送时间
    private function setDeliveryTime(){

        if(!isset($_REQUEST['send_date']) || empty($_REQUEST['send_date'])){
            returnJsonData('配送日期必须选择');
        }

        if(!isset($_REQUEST['send_start_time']) || empty($_REQUEST['send_start_time'])){
            returnJsonData('配送开始时间必须选择');
        }

        if(isset($_REQUEST['send_end_time']) && !empty($_REQUEST['send_end_time'])){
            if(strtotime($_REQUEST['send_end_time']) < strtotime($_REQUEST['send_end_time'])){
                returnJsonData('配送结束时间不能小于配送开始时间');
            }
        }
        //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 start
        $dataArray=array(
            'date'=>$_REQUEST['send_date']
        );
        $iserror=$this->preSale($dataArray);
        if($iserror==400){
            returnJsonData('抱歉，该日的拿破仑莓恋已爆单，您可选择其他的配送日期');
        }
        //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 end

        //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
        $retArry=$this->sendDateFun($_REQUEST['send_date'],"Gingerbread",$this->bill_array['goods']['general']);
        if($retArry["code"]==400){
            returnJsonData('抱歉，该日的"姜饼人"商品已爆单，您可选择其他的配送日期');
        }
        //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end

        //实例订单结算类
        $billCheckout = new billCheckout();

        $arg_array = array(
            'send_date' => $_REQUEST['send_date'],
            'send_start_time' => $_REQUEST['send_start_time'],
            'send_end_time' => $_REQUEST['send_end_time']
        );

        //配送站id
        $distribution_id = $this->bill_array['master']['distribution_id'];
        $check_result_array = $billCheckout->checkDistributionSendRestrict( $arg_array['send_date'], $arg_array['send_start_time'], $distribution_id );

        $this->bill_array['master']['explode_bill_sign'] = $check_result_array['h'];
        $this->bill_array['master']['send_date'] = $arg_array['send_date'];
        $this->bill_array['master']['send_start_time'] = $arg_array['send_start_time'];
        $this->bill_array['master']['send_end_time'] = $arg_array['send_end_time'];

        //wap配送时间标志
        if ($this->source == 'wap') {
            $this->bill_array['master']['is_wapTimeSelect'] = 1;
        }

        $this->setBillArray($arg_array);

    }

    /**
     * 使用积分
     */
    private function usePoints(){

        //检验会员登陆状态
        $this->login_status();

        if(!isset($_REQUEST['points'])){
            returnJsonData('请输入要抵扣金额的积分');
        }

        if(!is_money($_REQUEST['points'])){
            returnJsonData('输入的金额不正确，请重新输入');
        }

        if($_REQUEST['points'] < 0){
            returnJsonData('输入的金额不能小于0');
        }

        if(intval($_REQUEST['points'])%100 != 0){
            returnJsonData('积分使用小单位为100积分');
        }

        $pcustID = $this->pcustID;

        //用户使用积分数
        $input_points = $_REQUEST['points'];

        //如果实付金额小于积分使用金额，以实付金额为最大积分使用金额
        if(isset($this->bill_array['total_receivable_money'])){
            $total_receivable_money = $this->bill_array['total_receivable_money'];
            if($total_receivable_money*100 < $input_points){
                $input_points = $total_receivable_money*100;
            }
        }

        //换算金额数
        $points_price = round( $input_points/100, 2 );

        quanli_require('module/func/eai.func.php');

        $ebsigEai = eai_crm();
        $result = $ebsigEai->searchCustAccount($pcustID,G_POINTS_ID);

        if($result['code'] == 200){
            $useableAccount = $result['data']['useableAccount'];
            if($input_points > $useableAccount){
                returnJsonData('账户积分不够');
            }
        }else{
            returnJsonData($result['message'], $result['code']);
        }

        //记录积分使用信息
        $this->bill_array['use_points'] = array(
            'points' => $input_points,
            'bill_points_money' => $points_price
        );

        $this->setBillArray(null, $this->bill_array['use_points']);

    }

    /*
     * 取消使用积分
     */
    private function cancelUsePoints(){

        if(!isset($this->bill_array['use_points']) || empty($this->bill_array['use_points'])){
            returnJsonData('您当前没有使用积分，无需取消');
        }

        $points_money = $this->bill_array['use_points']['bill_points_money'];
        if(isset($this->bill_array['use_points'])){
            unset($this->bill_array['use_points']);
        }

        $this->setBillArray(null,$points_money);
    }

    /**
     * 使用代金卡
     */
    private function useCard(){

        if(!isset($_REQUEST['card_pwd']) || empty($_REQUEST['card_pwd'])){
            returnJsonData('请输入现金/专项卡密码');
        }

        $card_pwd = $_REQUEST['card_pwd'];

        //购物车商品
        $bill_goods_array = &$this->bill_array['goods'];

        if(!isset($bill_goods_array['general']) || empty($bill_goods_array['general'])){
            returnJsonData('请先向购物车中添加商品');
        }

        //检测应收金额
        $total_array = $this->totalCount(1);

        if($total_array['total_receivable_money'] <= 0){
            returnJsonData('货款已付清，无需再使用现金卡/专享卡');
        }

        if(isset($this->bill_array['use_card']['balance']) && $this->bill_array['use_card']['balance'] > 0){
            returnJsonData('没有可供现金/专项卡抵用金额的商品');
        }

        //加载类文件
        quanli_include('module/base/promotion/quanliCard.class.php');

        //实例化现金卡类
        $quanliCard = new quanliCard();

        if(!isset($this->bill_array['use_card'])){
            $this->bill_array['use_card'] = array(
                'balance' => 0,
                'detail' => array()
            );
        }

        //验证是否可以使用
        $result_array = $quanliCard->checkCard( $card_pwd, $bill_goods_array['general'],$this->bill_array['use_card'] );

        if($result_array['code'] == 200){

            $this->bill_array['card_array'][$card_pwd] = $card_pwd;
            $this->setBillArray(null, array('card_pwd' => $card_pwd, 'list' => $this->bill_array['use_card']['detail']));

        }else{
            returnJsonData( $result_array['message'], $result_array['code'] );
        }

    }

    /**
     * 使用优惠券
     */
    private function useCoupon(){

        //检验会员登陆状态
        $this->login_status();

        if (!isset($_REQUEST['code']) || empty($_REQUEST['code'])) {
            returnJsonData('请输入优惠券编码');
        }

        //加载类文件
        quanli_include('module/base/promotion/quanliCoupon.class.php');

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        $code = $_REQUEST['code'];
        $bill_array = & $this->bill_array;

        //检测应收金额
        $total_array = $this->totalCount(1);

        if($total_array['total_receivable_money'] <= 0){
            returnJsonData('已经没有可用于现金劵抵扣的金额');
        }

        /**
         * =====================================
         * 生成商品数组
         * =====================================
         */
        $goods_array = array();
        if (isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])) {
            foreach ($bill_array['goods']['general'] as &$list) {

                if(isset($list['is_buy']) && $list['is_buy'] == 0){
                    continue;
                }

                $goods_array[] = array(
                    'postID' => $list['postID'],
                    'price' => $list['price'],
                    'cityID'=> $list['cityID'],
                    'goodsAmount' => 1
                );
            }
        } else {
            returnJsonData('请先添加商品', 404);
        }
        /**
         * =====================================
         * 生成商品数组
         * =====================================
         */

        //检查优惠券
        $result_array = $ebsigCoupon->checkCoupon($code, $this->pcustID, $goods_array);

        if ($result_array['code'] == 200) {
            $coupon = array(
                'code' => $result_array['data']['code'],
                'amount' => $result_array['data']['amount'],
                'couponID' => $result_array['data']['couponID'],
                'couponType' => $result_array['data']['couponType'],
                'couponName' => $result_array['data']['couponName'],
                'useType' => $result_array['data']['useType']
            );

            //检查优惠券类型使用情况
            if(isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon']) && $coupon['useType'] == 1){
                $redCount = 0;
                foreach($bill_array['use_coupon'] as &$c){
                    if($c['useType'] == 1){
                        $redCount++;
                        break;
                    }
                }
                if($redCount > 0){
                    returnJsonData('此类型优惠券只能使用一次，请换成其他类型优惠券使用');
                }
            }

            $bill_array['use_coupon'][$coupon['code']] = $coupon;
            $this->setBillArray();

        } else {
            returnJsonData( $result_array['message'], $result_array['code'] );
        }

    }

    /**
     * 取消使用优惠券
     */
    private function cancelUseCoupon(){

        if(!isset($_REQUEST['code']) || empty($_REQUEST['code'])){
            returnJsonData('取消使用优惠券编码不能为空');
        }

        $code = $_REQUEST['code'];
        $use_coupon = &$this->bill_array['use_coupon'];

        if(isset($use_coupon[$code]))
            unset($use_coupon[$code]);

        $this->setBillArray(null, $code);

    }


    /**
     * 使用红包
     */
    private function useRedBag(){

        //检验会员登陆状态
        $this->login_status();

        if (!isset($_REQUEST['code']) || empty($_REQUEST['code'])) {
            returnJsonData('请输入优惠券编码');
        }

        //加载类文件
        quanli_include('module/base/promotion/quanliCoupon.class.php');

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        $code_array = $_REQUEST['code'];
        $bill_array = & $this->bill_array;

        /**
         * =====================================
         * 生成商品数组
         * =====================================
         */
        $goods_array = array();
        if (isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])) {
            foreach ($bill_array['goods']['general'] as &$list) {

                if(isset($list['is_buy']) && $list['is_buy'] == 0){
                    continue;
                }

                $goods_array[] = array(
                    'postID' => $list['postID'],
                    'cityID'=> $list['cityID'],
                    'price' => $list['price'],
                    'goodsAmount' => 1
                );
            }
        } else {
            returnJsonData('请先添加商品', 404);
        }
        /**
         * =====================================
         * 生成商品数组
         * =====================================
         */

        $message = array();
        foreach($code_array as &$code){

            $result_array = $ebsigCoupon->checkCoupon($code, $this->pcustID, $goods_array);
            if ($result_array['code'] == 200) {
                $coupon = array(
                    'code' => $result_array['data']['code'],
                    'amount' => $result_array['data']['amount'],
                    'couponID' => $result_array['data']['couponID'],
                    'couponType' => $result_array['data']['couponType'],
                    'couponName' => $result_array['data']['couponName'],
                    'useType' => $result_array['data']['useType']
                );

                $bill_array['use_coupon'][$coupon['code']] = $coupon;
            }else{
                $message[] = array(
                    'code' => $result_array['code'],
                    'red_code' => $code,
                    'message' => $result_array['message']
                );
            }
        }

        $this->setBillArray(null, $message );

    }


    /**
     * 查询账户下的红包、券
     */
    private function couponByUseType(){

        global $G_SHOP;

        if(!$G_SHOP->currentPCustID){
            returnJsonData('请先登录');
        }

        $useType = 'ALL';
        if(isset($_REQUEST['useType']) && !empty($_REQUEST['useType'])){
            $useType = $_REQUEST['useType'];
        }

        //引入优惠券类
        quanli_require('module/base/promotion/quanliCoupon.class.php');

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        $return_array = array();

        //获取当前城市ID
        $cityid = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        $args_array = array(
            'pcustID' => $G_SHOP->currentPCustID,
            'useType' => $useType,
            'used' => 1,
            'endDate' => $G_SHOP->sys_date,
            'page' => $_REQUEST['page'],
            'rp' => isset($_REQUEST['rp']) ? $_REQUEST['rp'] : 2,
            'sortname' => 'createTime',
            'sortorder' => 'DESC',
            'cityID' => $cityid
        );

        $coupon_code_array = $ebsigCoupon->searchCouponCode( $args_array );


        if(!$coupon_code_array){
            returnJsonData('没有找到可用的券或红包');
        }

        $return_array['coupon'] = $coupon_code_array;
        $return_array['paging'] = '';
        if($coupon_code_array){

            if($useType == 1){  //券
                $return_array['paging'] = shop_page($args_array['page'], $args_array['count'], $args_array['rp'], 'javascript: checkout.coupon.searchCoupon(%d);', $G_SHOP->smarty);
            }elseif($useType == 2){ //红包
                $return_array['paging'] = shop_page($args_array['page'], $args_array['count'], $args_array['rp'], 'javascript: checkout.coupon.serachRedBag(%d);', $G_SHOP->smarty);
            }

        }

        returnJsonData('ok', 200, $return_array);

    }

    /**
     * 订单总计算
     */
    public function totalCount( $return=false ){

        $total_array = array(
            'bill_receivable_money'            => 0,          //订单应收金额
            'bill_points'                        => 0,          //订单获取积分
            'bill_totalPaid'                    => 0,          //商品的实际成交总金额
            'total_amount'                      => 0,           //商品总数量
            'bill_accessories_money'           => 0,          //商品附件费用
            'deliver_feePaid'                   => 0,          //实际运费
            'bill_points_money'                 => 0,          //积分抵扣金额
            'bill_card_money'                   => 0,          //代金卡抵扣金额
            'bill_coupon_money'                 => 0,          //订单优惠券抵扣金额
            'total_subtract_money'             => 0,          //订单立减金额
            'use_card_list'                     => array(),
            'use_coupon_list'                   => array(),
            'goods_promotion'                   => array(),
            'bill_promotion'                    => array(),
            'donation'                           => '',
            'goods'                              => array(),
            'cut_rebate_money'                 => 0,            //会员折扣金额
            'rate'                               => 10,           //会员折扣
            'rank'                               => 1,            //会员等级
            'card_is_invoice'                  => 1,            //卡是否开发票
            'payTypeName'                       => '',          //付款方式名称
            'paymentName'                       => '',          //付现方式
            'discount_money'                     => 0,          //折扣抵扣金额(银行折扣、会员折扣)
            'erase_money'                       => 0            //抹去的小数金额
        );

        global $G_SHOP;

        $bill_array = &$this->bill_array;
        $bill_master_array = &$this->bill_array['master'];
        $bill_goods_array = &$this->bill_array['goods'];

        //验证购物车是否添加商品
        if(!isset($bill_goods_array['general']) || empty($bill_goods_array['general'])){
            return array('code' => 400, 'message' => '您还没有购买商品，请先添加商品', 'data' => $total_array);
        }

        quanli_require('module/base/promotion/promotionGoods.class.php');
        quanli_require('module/base/promotion/promotionBill.class.php');
        quanli_require('module/base/customer/quanliCust.class.php');

        //实例商品促销类
        $promotionGoods = new promotionGoods($G_SHOP->DBCA);

        //实例订单促销类
        $promotionBill = new promotionBill($G_SHOP->DBCA);

        //实例化会员类
        $quanliCust = new quanliCust();

        //获取当前城市ID
        $cityid = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        //配送日期
        $send_date = $bill_master_array['send_date'];

        //促销渠道
        if(isset($bill_master_array['billPromotion'])){
            $billPromotion = $bill_master_array['billPromotion'];
        }else{
            $billPromotion = 0;
        }

        //支付方式
        if(isset($bill_master_array['payTypeID'])){
            $payTypeID = $bill_master_array['payTypeID'];
            $total_array['payTypeName'] = $bill_array['master']['payTypeName'];
        }else{
            $payTypeID = 0;
        }

        //付款方式
        if (isset($bill_array['master']['payment_method_id'])) {
            $payment_method_id = $bill_array['master']['payment_method_id'];
            $total_array['paymentName'] = $bill_array['master']['payment_method_name'];

            if(isset($bill_array['master']['card_is_invoice']))
                $total_array['card_is_invoice'] = $bill_array['master']['card_is_invoice'];

        } else {
            $payment_method_id = 0;
        }

        //使用现金卡
        $use_card_array = array();
        if(isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail'])){
            $use_card_array = $bill_array['use_card']['detail'];
        }

        //使用优惠券
        $use_coupon = 0;
        if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
            $use_coupon = 1;
        }

        try{

            //获得会员等级信息
            $cust_rank_array = $quanliCust->getCustRank( $this->pcustID );

            //mod allen.qiang 20141028 农业银行信用卡五折购 start
            quanli_require('module/base/activity/activitySpike.class.php');
            $activityspike=new activitySpike();
            if($billPromotion == $activityspike->billPromotion)//是否秒杀活动
                $cust_rank_array['rate']=1; //会员等级折扣
            else if($billPromotion == $activityspike->billPromotion_lv5)//LV5五折购
                $cust_rank_array['rate']=1; //会员等级折扣
            else if($billPromotion == $activityspike->billPromotion_ny_xyk){//allen.qiang 20141028 农业银行信用卡五折购 add
                //是否含有一磅蛋糕
                $isbool=false;
                $general=$bill_goods_array['general'];
                foreach($general as &$goods){
                    if($goods['spec']=="1磅")
                        $isbool=true;
                }

                if(($bill_array['master']['payTypeID']==$activityspike->payTypeID_ny_xyk || $bill_array['master']['payment_method_id']==$activityspike->paymentID_ny_xyk) && $cityid==110 && $activityspike->nh_xyk_isDate() && $isbool && $activityspike->nh_xyk_num()>0){ //判断是否是用农业银行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
                    if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //农业银行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分、会员等级制度
                        $billPromotion=0;
                    }else{
                        $cust_rank_array['rate']=1; //会员等级折扣
                    }
                }else{
                    $billPromotion=0;
                }

            }
            //mod allen.qiang 20141028 农业银行信用卡五折购 end

            //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---start
            quanli_require('module/base/activity/activityCbc.class.php');
            //实例建设银行五折购活动类
            $activityCBC=new activityCbc();
            $_REQUEST["pcustID"]=$this->pcustID;
            $activity_master=$activityCBC->activity_master($_REQUEST);
            if($billPromotion == $activity_master["billPromotion"] ){
                //是否含有一磅蛋糕
                $isbool=false;
                $general=$bill_array['goods']['general'];
                foreach($general as &$goods){
                    if($goods['spec']=="1磅" && $goods['goodsName']!="悦时光")
                        $isbool=true;
                }
                if($bill_array['master']['payment_method_id']==$activity_master["paymentID_CBC"] && $cityid==110 && $activity_master["isDate"]==1 && $isbool && $activity_master["activity_num"]>0){ //判断是否是用建行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
                    if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //建行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分
                        $billPromotion=0;
                    }
                }else{
                    $billPromotion=0;
                }
            }
            //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---end

            //add by 20141220 allen.qiang  FUN-AC-0021-浦发银行五折购 ---start
            quanli_require('module/base/activity/activityPf.class.php');
            //实例浦发银行五折购活动类
            $activityPf=new activityPf();
            $_REQUEST["pcustID"]=$this->pcustID;
            $activity_pf=$activityPf->activity_master($_REQUEST);
            if($billPromotion == $activity_pf["billPromotion"] ){
                if( $activity_pf["activity_num"]<=0){ //判断浦发银行五折购是否已售罄
                    $billPromotion=0;
                    $bill_array['master']['billPromotion']=0;
                }
            }
            //add by 20141220 allen.qiang  FUN-AC-0021-浦发银行五折购 ---end

            //add by 20141229 allen.qiang  2014-12-29 FUN-AC-0033-BD农行五折购 ---start
            quanli_require('module/base/activity/activityBank.class.php');
            $activityBank=new activityBank();
            $_REQUEST["pcustID"]=$this->pcustID;
            $activity_bank=$activityBank->activity_master($_REQUEST,"activity_nh_xyk");
            if($billPromotion == $activity_bank["billPromotion"] ){
                if( $activity_bank["activity_num"]<=0){ //判断BD农行五折购是否已售罄
                    $billPromotion=0;
                    $bill_array['master']['billPromotion']=0;
                }
            }
            //add by 20141229 allen.qiang  2014-12-29 FUN-AC-0033-BD农行五折购 ---end

            $total_array['rank'] = $cust_rank_array['rankID'];
            if($cust_rank_array['rate'] < 1){
                $total_array['rate'] = $cust_rank_array['rate']*10;
            }

            $goods_array = array();
            $donation = array();
            foreach($bill_goods_array['general'] as $key=>&$goods){

                if(isset($goods['is_buy']) && $goods['is_buy'] == 0)
                    continue;

                //统计赠送配件
                if(isset($goods['fittings'])){
                    foreach($goods['fittings'] as $fitting){
                        if($fitting['forsale'] == 1){
                            continue;
                        }

                        $fitID = $fitting['fitID'];
                        if(isset($donation[$fitID])){
                            $donation[$fitID]['quantity']+=$fitting['quantity']*$goods['goods_amount'];
                        }else{
                            $donation[$fitID]['fitName'] = $fitting['fitName'];
                            $donation[$fitID]['quantity'] = $fitting['quantity']*$goods['goods_amount'];
                            $donation[$fitID]['unitName'] = $fitting['unitName'];
                        }
                    }
                }

                //计算购买配件
                if(isset($goods['buyFittings'])){
                    foreach($goods['buyFittings'] as &$fittings){
                        foreach($fittings as &$fit){
                            $total_array['bill_accessories_money'] += $fit['buyNum']*$fit['price'];
                        }
                    }
                }
                $accessories=$total_array['bill_accessories_money'];//配件的金额
                $goods['price'] = $goods['salePrice'];
                $promotion_array = $promotionGoods->searchGoodsPromotion($goods['postID'], $send_date, $billPromotion, $cityid, $payTypeID, $use_card_array, $use_coupon, $payment_method_id, $cust_rank_array['rankID'] );

                $promotion_discount_money = 0;      //促销折扣金额
                if($promotion_array){
                    $goods['goods_promotion'] = $promotion_array;
                    $goods_promotion = array();
                    foreach($promotion_array as &$promotion_goods) {
                        switch($promotion_goods['type']) {
                            case 1: //商品立减
                                $goods['price'] -= $promotion_goods['money'];
                                $goods_promotion[] = '[立减]' . $promotion_goods['remark'];
                                break;
                            case 2:  //商品特价
                                $goods['price'] = $promotion_goods['money'];
                                $goods_promotion[] = '[特价]' . $promotion_goods['remark'];
                                break;
                            case 6: //商品打折
                                $temp_goods_price = $goods['price'];
                                $goods['price'] = round($goods['price'] * $promotion_goods['money'], 2);
                                $promotion_discount_money += ($temp_goods_price - $goods['price']);
                                $goods_promotion[] = '[折扣]' . $promotion_goods['remark'];
                                break;
                        }
                    }

                    $total_array['goods_promotion'][$goods['postID']] = implode(' ', $goods_promotion);

                }else{
                    $goods['goods_promotion'] = null;
                }

                $promotion_discount_money *= $goods['goods_amount'];//商品折扣扣减金额
                $goods_price = $goods['price'];//会员折前价
                $goods['price'] = round($goods['price'] * $cust_rank_array['rate'], 2);//会员折后价

                $total_array['cut_rebate_money'] += ($goods_price - $goods['price']) * $goods['goods_amount'];//会员折扣扣减金额
                $total_array['discount_money'] += ( $total_array['cut_rebate_money'] + $promotion_discount_money );//折扣抵扣金额
                $total_array['total_amount'] += $goods['goods_amount'];
                $total_array['bill_totalPaid'] += $goods['price'] * $goods['goods_amount'];

                //购物车商品数组：用于订单促销
                $goods_array[$key] = array(
                    'postID' => $goods['postID'],
                    'price' => $goods['price'],
                    'goods_amount' => $goods['goods_amount']
                );
            }

            if(isset($bill_goods_array['general']) && !empty($bill_goods_array['general'])){
                $total_array['goods'] = $bill_goods_array['general'];
            }

            //记录会员等级折扣金额
            if($total_array['cut_rebate_money'] > 0){
                $bill_array['cut_rebate_money'] = $total_array['cut_rebate_money'];
            }else{
                $bill_array['cut_rebate_money'] = 0;
            }

            if(!empty($donation)){
                foreach($donation as $v){

                    $donation_str = $v['fitName'] . $v['quantity'] . $v['unitName'].'  ';
                    $total_array['donation'] .= $donation_str;
                }
            }
            //mod 20141124 sunqiang  FUN-BK-0034 运费规则调整 start
            $total_array['deliver_feePaid'] = isset($this->bill_array['master']['deliver_feePaid'])?$this->bill_array['master']['deliver_feePaid']:0.00; //运费
            //$total_array['deliver_feePaid'] = isset($this->bill_array['master']['deliver_fee'])?$this->bill_array['master']['deliver_fee']:0.00; //运费
            //mod 20141124 sunqiang  FUN-BK-0034 运费规则调整 end

            //订单促销
            $bill_promotion_array = $promotionBill->searchBillPromotion($goods_array, $send_date, $billPromotion, $cityid, $payTypeID, $use_card_array, $use_coupon, $payment_method_id, $cust_rank_array['rankID']);

            $bill_array['bill_promotion'] = null;

            if(isset($bill_promotion_array['meet'])){

                foreach($bill_promotion_array['meet'] as &$bill_promotion){

                    switch($bill_promotion['type']) {

                        case 1: //订单立减
                            $total_array['total_subtract_money'] += $bill_promotion['subtractMoney'];
                            $total_array['bill_promotion'][] = '[立减]' . $bill_promotion['remark'];
                            break;

                        case 2: //免运费
                            $total_array['deliver_feePaid'] = 0;
                            $total_array['bill_promotion'][] = '[免运费]' . $bill_promotion['remark'];
                            break;

                        case 3: //赠送优惠券
                            $total_array['bill_promotion'][] = '[赠券]' . $bill_promotion['remark'];
                            break;

                        case 4: //订单打折
                            $accessories=$total_array['bill_accessories_money'];//配件金额
                            $bill_totalPaid = $total_array['bill_totalPaid'];
                            $total_array['bill_totalPaid'] = round($total_array['bill_totalPaid'] * $bill_promotion['subtractMoney'], 2);
                            $total_array['bill_accessories_money'] = round($total_array['bill_accessories_money'] * $bill_promotion['subtractMoney'], 2);
                            $total_array['bill_promotion'][] = '[折扣]' . $bill_promotion['remark'];

                            //折扣抵扣累加
                            $total_array['discount_money'] += ($accessories-$total_array['bill_accessories_money']);
                            $total_array['discount_money'] += ($bill_totalPaid-$total_array['bill_totalPaid']);
                            break;
                    }
                }
                $bill_array['bill_promotion'] = $bill_promotion_array['meet'];

            }

            //积分抵扣金额
            if(isset($bill_array['use_points'])){
                $total_array['bill_points_money'] = $bill_array['use_points']['bill_points_money'];
            }

            //使用现金卡
            if(isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail'])){
                $total_array['use_card_list'] = $bill_array['use_card']['detail'];
                foreach($use_card_array as $card){
                    $total_array['bill_card_money'] += $card['deducation'];
                }
            }

            //使用优惠券
            if(isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])){
                $total_array['use_coupon_list'] = $bill_array['use_coupon'];
                foreach($bill_array['use_coupon'] as &$coupon){
                    if($coupon['useType'] == 1){
                        $total_array['bill_coupon_money'] += $coupon['amount'];
                    }elseif($coupon['useType'] == 2){
                        $total_array['bill_card_money'] += $coupon['amount'];
                    }
                }
            }

            //====================================================
            //===================订单应收金额=====================
            //====================================================
            $total_array['total_receivable_money'] = $total_array['bill_totalPaid']
                + $total_array['bill_accessories_money']
                - $total_array['total_subtract_money']
                - $total_array['bill_coupon_money']
                - $total_array['bill_card_money']
                - $total_array['bill_points_money'];


            $total_array['total_points'] = floor($total_array['total_receivable_money']/4);

            if($total_array['total_receivable_money'] <=0){
                $total_array['total_receivable_money'] = 0;
            }

            $total_array['total_receivable_money'] += $total_array['deliver_feePaid'];


            //LV5五折购 只走五折 diandong
            if(isset($bill_array['master']['billPromotion']) && $bill_array['master']['billPromotion'] == $activityspike->billPromotion_lv5)//LV5五折购
            {
                $total_array['bill_totalPaid']=   $goods['price'];
               $total_array['bill_accessories_money']=$accessories;
                //商品金额/2+配件费+服务费
                $total_array['total_receivable_money']=$goods['price']+$total_array['bill_accessories_money']+ $total_array['deliver_feePaid'] ;

            }


            //去零取整
            if(intval($total_array['total_receivable_money']) != $total_array['total_receivable_money']){
                $total_array['erase_money'] = $total_array['total_receivable_money'] - intval($total_array['total_receivable_money']);
                $total_array['total_receivable_money'] = intval($total_array['total_receivable_money']);
            }

            if($return){
                return $total_array;
            }else{
                $this->setBillArray(null, $total_array);
            }

        }catch (Exception $e){

            if($e->getCode() > 0){
                returnJsonData($e->getMessage(), $e->getCode());
            }else{
                error_log($e->getMessage());
                returnJsonData('系统错误', 500);
            }
        }
    }


    /**
     * 选择支付方式或付款方式
     */
    private function choosePay(){
        if(!isset($_REQUEST['payTypeID']) || empty($_REQUEST['payTypeID'])){
            returnJsonData('支付方式必须选择');
        }
        $payTypeID = $_REQUEST['payTypeID'];

        $paymentID = 0;
        if(isset($_REQUEST['paymentID']) && !empty($_REQUEST['paymentID'])){
            $paymentID = $_REQUEST['paymentID'];
        }

        //加载支付方式类
        quanli_require('module/base/system/sysPayment.class.php');

        $bill_master_array = &$this->bill_array['master'];

        //实例支付方式类
        $sysPayment = new sysPayment();

        $arg_array = array(
            'payTypeID' => $payTypeID,
            'source' => $this->source
        );
        error_log(print_r($arg_array,1));
        $payType_array = $sysPayment->searchPayType($arg_array);
        if(!$payType_array){
            returnJsonData('没有此支付方式，请重新选择支付方式!');
        }

        $payment_method_id = 0;
        $payment_method_name = '';
        $payment_method_type = 0;
        $card_is_invoice = 1;
        if($paymentID){
            $arg_array = array(
                'payTypeID' => $payTypeID,
                'id' => $paymentID
            );

            $payment_array = $sysPayment->searchPaymentMethod($arg_array);

            if(!$payment_array)
                returnJsonData('没有此支付方式，请重新选择支付方式');

            $payment_method_id = $paymentID;
            $payment_method_name = $payment_array[0]['name'];
            $payment_method_type = $payment_array[0]['type'];
            $card_is_invoice = $payment_array[0]['is_invoice'];
        }

        $bill_master_array['payTypeID'] = $payTypeID;
        $bill_master_array['pay_type'] = $payType_array[0]['type'];
        $bill_master_array['payTypeName'] = $payType_array[0]['payTypeName'];
        $bill_master_array['payment_method_id'] = $payment_method_id;
        $bill_master_array['payment_method_name'] = $payment_method_name;
        $bill_master_array['payment_method_type'] = $payment_method_type;
        $bill_master_array['card_is_invoice'] = $card_is_invoice;

        $this->cust_buy_log['payTypeID'] = $bill_master_array['payTypeID'];
        $this->cust_buy_log['pay_type'] = $bill_master_array['pay_type'];
        $this->cust_buy_log['payment_method_id'] = $bill_master_array['payment_method_id'];
        $this->cust_buy_log['is_invoice'] = $bill_master_array['card_is_invoice'];

        $c = array(1);
        $this->setBillArray($c);

    }

    /**
     * 购买配件
     */
    private function buyFittings(){

        if(!isset($_REQUEST['postID']) || empty($_REQUEST['postID'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['indexKey']) || !is_numeric($_REQUEST['indexKey'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['fit']) || empty($_REQUEST['fit'])){
            returnJsonData('请输入购买配件的数量');
        }

        $postID = $_REQUEST['postID'];
        $indexKey = $_REQUEST['indexKey'];
        $fit = $_REQUEST['fit'];

        $bill_goods_array = &$this->bill_array['goods'];
        if(!isset($bill_goods_array['general']) || empty($bill_goods_array['general'])){
            returnJsonData('购物车没有商品，请刷新页面');
        }

        if(!isset($bill_goods_array['general'][$postID])){
            returnJsonData('参数错误');
        }

        $bill_goods_array['general'][$postID]['buyFittings'][$indexKey] = $fit;

        $this->setBillArray();

    }

    /**
     * 取消使用现金卡
     */
    private function cancelUseCard(){
        global $G_SHOP;

        if(!isset($_REQUEST['card_pwd']) || empty($_REQUEST['card_pwd'])){
            returnJsonData('参数错误');
        }
        $card_pwd = $_REQUEST['card_pwd'];

        //加载类文件
        quanli_include('module/base/promotion/quanliCard.class.php');

        //实例化现金卡类
        $quanliCard = new quanliCard( $G_SHOP->DBCA );

        if(!isset($this->bill_array['use_card']['detail'][$card_pwd])){

            returnJsonData('ok', 200, $this->bill_array['use_card']['detail']);

        }
        $use_card = &$this->bill_array['use_card']['detail'];

        //删除代金卡
        unset($use_card[$card_pwd]);
        unset($this->bill_array['card_array'][$card_pwd]);

        foreach($this->bill_array['goods']['general'] as &$goods) {

            $goods['use_card'] = array();
            $goods['card_deducation'] = 0;
        }

        $new_use_card_array = array(
            'balance' => 0,
            'detail' => array()
        );

        if (count($use_card) > 0) {

            foreach($use_card as &$card) {

                //验证是否已经使用
                $result_array = $quanliCard->checkCard( $card['card_pwd'], $this->bill_array['goods']['general'], $new_use_card_array );

                if($result_array['code'] == 200){
                    $card_pwd = $result_array['data'];
                    $this->bill_array['card_array'][$card_pwd] = $card_pwd;
                }

            }
        }

        $this->bill_array['use_card'] = $new_use_card_array;
        $this->setBillArray(null, array('card_pwd' => $card_pwd, 'list' => $new_use_card_array['detail']));

    }

    /**
     * 记录会员收货地址
     */
    private function setdeliverID(){

        if(!isset($this->cust_buy_log['deliverID']) || empty($this->cust_buy_log['deliverID'])){
            returnJsonData('参数错误');
        }

        global $G_SHOP;

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        //查询会员收货地址
        if (!$billCheckout->getDeliver( $this->bill_array['master'], $this->cust_buy_log, $this->cust_buy_log['deliverID'] )) {
            returnJsonData('收货地址信息没有找到，请选择其他收货地址');
        }

        unset($this->bill_array['master']['sendTypeID']);
        unset($this->bill_array['master']['payTypeID']);
        unset($this->bill_array['master']['payTypeName']);
        unset($this->bill_array['master']['pay_type']);
        unset($this->bill_array['master']['payment_method_id']);
        unset($this->bill_array['master']['payment_method_name']);
        unset($this->bill_array['master']['payment_method_type']);

        $this->setBillArray();

    }

    /**
     * 记录支付方式和付款方式
     */
    private function setPayType(){

        if(!isset($this->cust_buy_log['payTypeID']) || !is_numeric($this->cust_buy_log['payTypeID'])){
            returnJsonData('支付方式id错误');
        }

        if(!isset($this->cust_buy_log['pay_type']) || !is_numeric($this->cust_buy_log['pay_type'])){
            returnJsonData('支付方式类型错误');
        }

        if(!isset($this->cust_buy_log['payment_method_id']) || !is_numeric($this->cust_buy_log['payment_method_id'])){
            returnJsonData('付款方式id错误');
        }

        global $G_SHOP;

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        $bill_master_array = &$this->bill_array['master'];
        $cust_buy_log = &$this->cust_buy_log;

        if($cust_buy_log['payTypeID']){

            $billCheckout->getPayTypeList( $this->source,$bill_master_array,$cust_buy_log );
            $bill_master_array['payment_type'] = isset($cust_buy_log['payment_type'])?$cust_buy_log['payment_type']:0;

        }else{
            $bill_master_array['payTypeID'] = $cust_buy_log['payTypeID'];
            $bill_master_array['pay_type'] = $cust_buy_log['pay_type'];
            $bill_master_array['payment_method_id'] = $cust_buy_log['payment_method_id'];
            $bill_master_array['payment_type'] = isset($cust_buy_log['payment_type'])?$cust_buy_log['payment_type']:0;

        }

        $this->setBillArray();

    }

    /**
     * 记录生日牌
     */
    private function setBirthdayCard(){

        if(!isset($_REQUEST['postID']) || empty($_REQUEST['postID'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['key']) || !is_numeric($_REQUEST['key'])){
            returnJsonData('参数错误');
        }

        $postID = $_REQUEST['postID'];
        $key = $_REQUEST['key'];

        $bill_array = &$this->bill_array;
        $bill_goods_array = &$bill_array['goods'];

        if(!isset($bill_goods_array['general'])){
            returnJsonData('没有商品，请先添加商品');
        }

        if(isset($bill_goods_array['general'][$postID])){

            if(!isset($bill_goods_array['general'][$postID]['birthday_array'])){
                $bill_goods_array['general'][$postID]['birthday_array'] = array();
            }

            $bill_goods_array['general'][$postID]['birthday_array'][$key] = $_REQUEST['birthday_card'];

        }

        $this->setBillArray();

    }

    /**
     * 记录订单备注
     */
    private function setBillRemark(){

        if(!isset($_REQUEST['remark'])){
            returnJsonData('缺少参数');
        }

        $this->bill_array['remark'] = $_REQUEST['remark'];

        $this->setBillArray();

    }

    /**
     * 会员发票设置
     */
    private function setBillInvoice(){

        if(!isset($_REQUEST['invoice_content_id'], $_REQUEST['invoice_content'], $_REQUEST['invoice_title_type'], $_REQUEST['invoice_title'])){
            returnJsonData('缺少参数');
        }

        if(!is_numeric($_REQUEST['invoice_content_id']) || !is_numeric($_REQUEST['invoice_title_type'])){
            returnJsonData('参数错误');
        }

        if(empty($_REQUEST['invoice_title_type'])){
            returnJsonData('缺少参数');
        }

        if($_REQUEST['invoice_title_type'] !=1 && empty($_REQUEST['invoice_title_type'])){
            returnJsonData('缺少参数');
        }

        if(empty($_REQUEST['invoice_content_id']))
            $_REQUEST['invoice_content'] = null;

        $this->bill_array['invoice'] = array(
            'invoice' => 1,
            'invoice_content_id' => $_REQUEST['invoice_content_id'],
            'invoice_content' => $_REQUEST['invoice_content'],
            'invoice_title_type' => $_REQUEST['invoice_title_type'],
            'invoice_title' => $_REQUEST['invoice_title']
        );

        $this->setBillArray();
    }
	
    //add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --start
    public function baodan(){
    	$distribution_id =$_POST['distribution_id'];
    	
    	$send_date	=  $_POST['send_date'];

    	quanli_include('module/base/system/itemHandler.class.php');
    	$itemHandler = new itemHandler();
    	//配送开始时间
    	$item_array['itemCategoryID'] = 9;
    	$send_start_time = $itemHandler->searchItem( $item_array );
    	//通过遍历每一个数字来判断是否爆单
    	for($i = 0;$i<=count($send_start_time);$i++){
    		//实例订单结算类
    		$billCheckout = new billCheckout();
    		$result = $billCheckout->checkDistributionSendRestrict( $send_date, $send_start_time[$i]['itemName'], $distribution_id );
    		if($result['h'] == 1){
    			$send_start_time[$i]['h'] = 1;

    			
    		}
    	}
    	echo json_encode($send_start_time);    	
    }
    //add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --end



/*
*  拿破仑莓恋预售（配送日期磅数）web下单
*  @package ajax
*  @backend  shop
*  @author   allen.qiang <allen.qiang@fistforward.com>
*  20141126 add by FUN-AC-0022-拿破仑莓恋预售
*  $reust 日期
*/
    private function preSale($dateArray){
        quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
        global $G_SHOP;
        //获取配送日期
        $date=$dateArray['date'];
        //拿破仑莓恋SKU数组字符串
        $activity_config = new activityConfig('pre_sale'); //活动配置
        $config_array = $activity_config->config;
        //实例化商品类
        $goodsEdit=$config_array['goodsEdit'];//活动商品SKU 基础设置ID
        $sys_sql="SELECT itemName FROM sys_item WHERE itemCategoryID=?";
        $sys_query=$G_SHOP->DBCA->stmt_query($sys_sql,'s',$goodsEdit);
        $sys='';

        foreach($sys_query as $sys_array){
            $sys.="'".$sys_array->itemName."',";
            $arr[]=$sys_array->itemName;
        }
        $sys = substr($sys,0,strlen($sys)-1);

        //查询所选配送日期非取消状态订单中拿破仑莓恋的磅数信息
        $goods_sql="SELECT b2.product_code as product_code FROM  bill_master AS b1  RIGHT JOIN bill_goods AS b2  ON b1.bill_no=b2.bill_no WHERE b2.product_code IN ( ".$sys."  )  AND  b1.send_date= ? AND b1.bill_status <> ?";
        $data=$G_SHOP->DBCA->stmt_query($goods_sql,'ss',$date,10);
        $is=0;
        $pounds=0;

        foreach($this->bill_array['goods']['general'] as $goods){
            if(in_array($goods['product_code'],$arr)){
                $pounds+=substr($goods['product_code'],-1,1)*$goods['goods_amount'];
                //$is==1 则含有拿破仑莓恋蛋糕
                $is=1;
            }
        }
        if(!empty($data)){
            foreach($data as $dataProduct){
                $pounds+=substr($dataProduct->product_code,-1,1);
            }
        }
        //购物车里有拿破仑莓恋蛋糕 && 配送日期当天的拿破仑莓恋的配送量
        if($is==1 && ($pounds>$config_array['number'] )){
            return 400;
        }else{
            return 200;
        }
    }

    /*
  *  拿破仑莓恋预售（配送日期磅数）400下单
  *  @package ajax
  *  @backend  shop
  *  @author   allen.qiang <allen.qiang@fistforward.com>
  *  20141126 add by FUN-AC-0022-拿破仑莓恋预售
  *  $reust 日期
  */
    private function pre_sale(){
        quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
        global $G_SHOP;
        //获取配送日期
        $date=$_REQUEST['sendDate'];
        //获取商品信息
        $goods_info=$_REQUEST['goods'];
        //拿破仑莓恋SKU数组字符串
        //拿破仑莓恋SKU数组字符串
        $activity_config = new activityConfig('pre_sale'); //活动配置
        $config_array = $activity_config->config;
        //实例化商品类
        $goodsEdit=$config_array['goodsEdit'];//活动商品SKU 基础设置ID
        $sys_sql="SELECT itemName FROM sys_item WHERE itemCategoryID=?";
        $sys_query=$G_SHOP->DBCA->stmt_query($sys_sql,'s',$goodsEdit);
        $sys='';

        foreach($sys_query as $sys_array){
            $sys.="'".$sys_array->itemName."',";
            $arr[]=$sys_array->itemName;
        }
        $sys = substr($sys,0,strlen($sys)-1);
        //查询所选配送日期非取消状态订单中拿破仑莓恋的磅数信息
        $goods_sql="SELECT b2.product_code as product_code FROM  bill_master AS b1  RIGHT JOIN bill_goods AS b2  ON b1.bill_no=b2.bill_no WHERE b2.product_code IN ( ".$sys."  )  AND  b1.send_date= ? AND b1.bill_status <> ?";
        $data=$G_SHOP->DBCA->stmt_query($goods_sql,'ss',$date,10);
        //$is==0 则没有拿破仑莓恋蛋糕
        $is=0;
        $pounds=0;
        foreach($goods_info as $goods){
            if($goods['goodsName']=='拿破仑莓恋'){
                $pounds+=substr($goods['spec'],0,1)*$goods['goods_amount'];
                //$is==1 则含有拿破仑莓恋蛋糕
                $is=1;
            }
        }
        if(!empty($data)){
            foreach($data as $dataProduct){
                $pounds+=substr($dataProduct->product_code,-1,1);
            }
        }
        //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
        $message=""; //返回消息
        $isbool=true; //是否有爆单的商品

        //购物车里有拿破仑莓恋蛋糕 && 配送日期当天的拿破仑莓恋的配送量
        if($is==1 && ($pounds>$config_array['number'] )){
            $isbool=false;
            $message="'拿破仑莓恋',";
        }
        //判断‘姜饼人’商品是否爆单
        $retArry=$this->sendDateFun($date,"Gingerbread",$goods_info);
        if($retArry["code"]==400){
            $isbool=false;
            $message.="'姜饼人',";
        }
        $message = substr($message,0,strlen($message)-1);
        if($isbool){
            returnJsonData("库存暂余",200);
        }else{
            returnJsonData($message,400);
        }
        //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end

        //del by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
        //购物车里有拿破仑莓恋蛋糕 && 配送日期当天的拿破仑莓恋的配送量
        /*if($is==1 && ($pounds>$config_array['number'] )){
            returnJsonData('库存不足',400);
        }else{
            returnJsonData('库存暂余',200);
        }*/
        //del by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end
    }

 /* 根据日期判断活动商品是否超过限定磅数
 *  @$date 配送日期
 *  @$activity_name  活动名称
 *  @$goods_info 购物车数组
 *  @author   allen.qiang allen.qiang@fistforward.com
 *  20141211 add by FUN-AC-0029-姜饼项目
 *  return array()
 */
    public function sendDateFun($date,$activity_name,$goods_info){
        quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
        global $G_SHOP;
        //实例化活动配置类
        $activity_config = new activityConfig($activity_name); //活动配置
        $config_array = $activity_config->config;
        $sku_arry=$config_array['sku'];//活动商品SKU

        if(isset($config_array["baodanEndData"])){
            $activity_end_time = date('Y-m-d' ,strtotime($config_array['baodanEndData'])); //每日限定磅数截止日期
            if($date>$activity_end_time){
                return array(
                    'code' => 200,
                    'message' => "库存不限制"
                );
            }
        }

        //查询所选配送日期非取消状态订单中活动商品的磅数信息
        $goods_sql="SELECT b2.product_code as product_code FROM  bill_master AS b1  RIGHT JOIN bill_goods AS b2  ON b1.bill_no=b2.bill_no WHERE b2.product_code IN ( ".$sku_arry."  )  AND  b1.send_date= ? AND b1.bill_status <> ?";
        $goodsArry=$G_SHOP->DBCA->stmt_query($goods_sql,'ss',$date,10);
        $is=0;
        $pounds=0;

        foreach($goods_info as $goods){
            if(strstr($sku_arry,strtolower($goods['product_code']) )){ //判断是否是活动商品编码
                $pounds+=substr($goods['product_code'],-1,1)*$goods['goods_amount'];
                $is=1;
            }
        }
        if(!empty($goodsArry)){
            foreach($goodsArry as $dataProduct){
                $pounds+=substr($dataProduct->product_code,-1,1);
            }
        }

        //购物车里有活动商品 && 配送日期当天的活动商品的配送量
        if($is==1 && ($pounds>$config_array['number'] )){
            return array(
                'code' => 400,
                'message' => "库存不足"
            );
        }else{
            return array(
                'code' => 200,
                'message' => "库存暂余"
            );
        }
    }

    /**
     * 记录生日牌选择状态
     */
    private function bs_ck(){

        if(!isset($_REQUEST['postID']) || empty($_REQUEST['postID'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['key']) || !is_numeric($_REQUEST['key'])){
            returnJsonData('参数错误');
        }

        $postID = $_REQUEST['postID'];
        $key = $_REQUEST['key'];

        $bill_array = &$this->bill_array;
        $bill_goods_array = &$bill_array['goods'];

        if(!isset($bill_goods_array['general'])){
            returnJsonData('没有商品，请先添加商品');
        }

        if(isset($bill_goods_array['general'][$postID])){

            if(!isset($bill_goods_array['general'][$postID]['bs_ck'])){
                $bill_goods_array['general'][$postID]['bs_ck'] = array();
            }

            $bill_goods_array['general'][$postID]['bs_ck'][$key] = $_REQUEST['bs_ck'];

        }

        $this->setBillArray();
    }


    /**
     * 记录生日蜡烛选择状态
     */
    private function candle_ck(){

        if(!isset($_REQUEST['postID']) || empty($_REQUEST['postID'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['key']) || !is_numeric($_REQUEST['key'])){
            returnJsonData('参数错误');
        }

        $postID = $_REQUEST['postID'];
        $key = $_REQUEST['key'];

        $bill_array = &$this->bill_array;
        $bill_goods_array = &$bill_array['goods'];

        if(!isset($bill_goods_array['general'])){
            returnJsonData('没有商品，请先添加商品');
        }

        if(isset($bill_goods_array['general'][$postID])){

            if(!isset($bill_goods_array['general'][$postID]['candle_ck'])){
                $bill_goods_array['general'][$postID]['candle_ck'] = array();
            }

            $bill_goods_array['general'][$postID]['candle_ck'][$key] = $_REQUEST['candle_ck'];

        }

        $this->setBillArray();
    }

    /**
     * 订单总计算
     * add by 2015-01-22 allen.qiang FUN-AC-0037-情人节活动
     */
    public function totalCount_valentine( $return=false ){

        $total_array = array(
            'bill_receivable_money'            => 0,          //订单应收金额
            'bill_points'                        => 0,          //订单获取积分
            'bill_totalPaid'                    => 0,          //商品的实际成交总金额
            'total_amount'                      => 0,           //商品总数量
            'bill_accessories_money'           => 0,          //商品附件费用
            'deliver_feePaid'                   => 0,          //实际运费
            'bill_points_money'                 => 0,          //积分抵扣金额
            'bill_card_money'                   => 0,          //代金卡抵扣金额
            'bill_coupon_money'                 => 0,          //订单优惠券抵扣金额
            'total_subtract_money'             => 0,          //订单立减金额
            'use_card_list'                     => array(),
            'use_coupon_list'                   => array(),
            'goods_promotion'                   => array(),
            'bill_promotion'                    => array(),
            'donation'                           => '',
            'goods'                              => array(),
            'cut_rebate_money'                 => 0,            //会员折扣金额
            'rate'                               => 10,           //会员折扣
            'rank'                               => 1,            //会员等级
            'card_is_invoice'                  => 1,            //卡是否开发票
            'payTypeName'                       => '',          //付款方式名称
            'paymentName'                       => '',          //付现方式
            'discount_money'                     => 0,          //折扣抵扣金额(银行折扣、会员折扣)
            'erase_money'                       => 0            //抹去的小数金额
        );

        global $G_SHOP;

        $bill_array = &$this->bill_array;
        $bill_master_array = &$this->bill_array['master'];
        $bill_goods_array = &$this->bill_array['goods'];

        //验证购物车是否添加商品
        if(!isset($bill_goods_array['general']) || empty($bill_goods_array['general'])){
            return array('code' => 400, 'message' => '您还没有购买商品，请先添加商品', 'data' => $total_array);
        }

        quanli_require('module/base/promotion/promotionGoods.class.php');
        quanli_require('module/base/promotion/promotionBill.class.php');
        quanli_require('module/base/customer/quanliCust.class.php');

        //实例商品促销类
        $promotionGoods = new promotionGoods($G_SHOP->DBCA);

        //实例订单促销类
        $promotionBill = new promotionBill($G_SHOP->DBCA);

        //实例化会员类
        $quanliCust = new quanliCust();

        //获取当前城市ID
        $cityid = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        //配送日期
        $send_date = $bill_master_array['send_date'];

        //促销渠道
        if(isset($bill_master_array['billPromotion'])){
            $billPromotion = $bill_master_array['billPromotion'];
        }else{
            $billPromotion = 0;
        }

        //支付方式
        if(isset($bill_master_array['payTypeID'])){
            $payTypeID = $bill_master_array['payTypeID'];
            $total_array['payTypeName'] = $bill_array['master']['payTypeName'];
        }else{
            $payTypeID = 0;
        }

        //付款方式
        if (isset($bill_array['master']['payment_method_id'])) {
            $payment_method_id = $bill_array['master']['payment_method_id'];
            $total_array['paymentName'] = $bill_array['master']['payment_method_name'];

            if(isset($bill_array['master']['card_is_invoice']))
                $total_array['card_is_invoice'] = $bill_array['master']['card_is_invoice'];

        } else {
            $payment_method_id = 0;
        }

        //使用现金卡
        $use_card_array = array();
        if(isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail'])){
            $use_card_array = $bill_array['use_card']['detail'];
        }

        //使用优惠券
        $use_coupon = 0;
        if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
            $use_coupon = 1;
        }

        try{

            //获得会员等级信息
            $cust_rank_array = $quanliCust->getCustRank( $this->pcustID );

            $total_array['rank'] = $cust_rank_array['rankID'];
            if($cust_rank_array['rate'] < 1){
                $total_array['rate'] = $cust_rank_array['rate']*10;
            }

            $goods_array = array();
            $donation = array();
            foreach($bill_goods_array['general'] as $key=>&$goods){

                if(isset($goods['is_buy']) && $goods['is_buy'] == 0)
                    continue;

                //统计赠送配件
                if(isset($goods['fittings'])){
                    foreach($goods['fittings'] as $fitting){
                        if($fitting['forsale'] == 1){
                            continue;
                        }

                        $fitID = $fitting['fitID'];
                        if(isset($donation[$fitID])){
                            $donation[$fitID]['quantity']+=$fitting['quantity']*$goods['goods_amount'];
                        }else{
                            $donation[$fitID]['fitName'] = $fitting['fitName'];
                            $donation[$fitID]['quantity'] = $fitting['quantity']*$goods['goods_amount'];
                            $donation[$fitID]['unitName'] = $fitting['unitName'];
                        }
                    }
                }

                //计算购买配件
                if(isset($goods['buyFittings'])){
                    foreach($goods['buyFittings'] as &$fittings){
                        foreach($fittings as &$fit){
                            $total_array['bill_accessories_money'] += $fit['buyNum']*$fit['price'];
                        }
                    }
                }

                $goods['price'] = $goods['salePrice'];

                $promotion_discount_money = 0;      //促销折扣金额
                $temp_goods_price = $goods['price'];
                $discount="";
                if($payment_method_id!=0 && $payTypeID!=0){
                    $discount="货到付款享9.7折优惠";
                    $goods['price'] = round($goods['price'] * 0.97, 2);
                }
                else if($payTypeID!=0){
                    $discount="在线支付享9.5折优惠";
                    $goods['price'] = round($goods['price'] * 0.95, 2);
                }

                $promotion_discount_money += ($temp_goods_price - $goods['price']);
                if($discount!="")
                    $goods_promotion[] = '[折扣]'.$discount;
                if($cust_rank_array['rate']<1)
                    $goods_promotion[] = '</br>[折扣]level '.$cust_rank_array['rankID'].'会员'.($cust_rank_array['rate']*10).'折';
                $total_array['goods_promotion'][$goods['postID']] = implode(' ', $goods_promotion);

                $promotion_discount_money *= $goods['goods_amount'];//商品折扣扣减金额
                $goods_price = $goods['price'];//会员折前价
                $goods['price'] = round($goods['price'] * $cust_rank_array['rate'], 2);//会员折后价

                $total_array['cut_rebate_money'] += ($goods_price - $goods['price']) * $goods['goods_amount'];//会员折扣扣减金额
                $total_array['discount_money'] += ( $total_array['cut_rebate_money'] + $promotion_discount_money );//折扣抵扣金额
                $total_array['total_amount'] += $goods['goods_amount'];
                $total_array['bill_totalPaid'] += $goods['price'] * $goods['goods_amount'];


            }

            if(isset($bill_goods_array['general']) && !empty($bill_goods_array['general'])){
                $total_array['goods'] = $bill_goods_array['general'];
            }

            //记录会员等级折扣金额
            if($total_array['cut_rebate_money'] > 0){
                $bill_array['cut_rebate_money'] = $total_array['cut_rebate_money'];
            }else{
                $bill_array['cut_rebate_money'] = 0;
            }

            if(!empty($donation)){
                foreach($donation as $v){

                    $donation_str = $v['fitName'] . $v['quantity'] . $v['unitName'].'  ';
                    $total_array['donation'] .= $donation_str;
                }
            }

            $total_array['deliver_feePaid'] = isset($this->bill_array['master']['deliver_feePaid'])?$this->bill_array['master']['deliver_feePaid']:0.00; //运费

            //积分抵扣金额
            if(isset($bill_array['use_points'])){
                $total_array['bill_points_money'] = $bill_array['use_points']['bill_points_money'];
            }

            //使用现金卡
            if(isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail'])){
                $total_array['use_card_list'] = $bill_array['use_card']['detail'];
                foreach($use_card_array as $card){
                    $total_array['bill_card_money'] += $card['deducation'];
                }
            }

            //使用优惠券
            if(isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])){
                $total_array['use_coupon_list'] = $bill_array['use_coupon'];
                foreach($bill_array['use_coupon'] as &$coupon){
                    if($coupon['useType'] == 1){
                        $total_array['bill_coupon_money'] += $coupon['amount'];
                    }elseif($coupon['useType'] == 2){
                        $total_array['bill_card_money'] += $coupon['amount'];
                    }
                }
            }

            //====================================================
            //===================订单应收金额=====================
            //====================================================
            $total_array['total_receivable_money'] = $total_array['bill_totalPaid']
                + $total_array['bill_accessories_money']
                - $total_array['total_subtract_money']
                - $total_array['bill_coupon_money']
                - $total_array['bill_card_money']
                - $total_array['bill_points_money'];


            $total_array['total_points'] = floor($total_array['total_receivable_money']/4);

            if($total_array['total_receivable_money'] <=0){
                $total_array['total_receivable_money'] = 0;
            }

            $total_array['total_receivable_money'] += $total_array['deliver_feePaid'];

            //去零取整
            if(intval($total_array['total_receivable_money']) != $total_array['total_receivable_money']){
                $total_array['erase_money'] = $total_array['total_receivable_money'] - intval($total_array['total_receivable_money']);
                $total_array['total_receivable_money'] = intval($total_array['total_receivable_money']);
            }

            if($return){
                return $total_array;
            }else{
                $this->setBillArray(null, $total_array);
            }

        }catch (Exception $e){

            if($e->getCode() > 0){
                returnJsonData($e->getMessage(), $e->getCode());
            }else{
                error_log($e->getMessage());
                returnJsonData('系统错误', 500);
            }

        }

    }

}